package com.example.esp32;

import static android.content.ContentValues.TAG;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class pew extends AppCompatActivity {
    String zcc;
    List<ScanResult> able;
    private ListView listView;
    private WifiManager wifiManager;
    private final List<getValue> ddList = new ArrayList<getValue>();
    adapterwifi adapter = new adapterwifi(pew.this, ddList);
    private ImageButton daa, ble;
    private EditText edit_one;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ProgressDialog progressDialog1 = new ProgressDialog(this);
        progressDialog1.setMessage("正在加载中");
        progressDialog1.show();
        setContentView(R.layout.pew);
        listView = findViewById(R.id.list);


        SwipeRefreshLayout srl_my_refresh = findViewById(R.id.liss);

        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                progressDialog1.dismiss();
                two();
//                two();
//                wifi();
//                two();
                
            }
        }, 2000);
        //第二步，设置 下拉刷新时的颜色
        srl_my_refresh.setColorSchemeColors(Color.parseColor("#ff0000"), Color.parseColor("#00ff00"));
        //监听 刷新是回调
        srl_my_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                srl_my_refresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        srl_my_refresh.setRefreshing(false);
                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                        Boolean OO = sharedPreferences.getBoolean("wifiabd", false);
                        if (!OO) {
                            two();
                        } else {
                            scawifi();
                        }

                    }
                }, 30);
            }
        });

//ListView item 的的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String a=((TextView)view).getText().toString();
//                if(position==0){Toast.makeText(pew.this,"这个不能点", Toast.LENGTH_SHORT).show();
//                }
//                else{
//                    tck(a);

                String ssid = ((TextView) view.findViewById(R.id.ssid)).getText().toString();

                String jmfs = ((TextView) view.findViewById(R.id.jmfs)).getText().toString();
                if (jmfs.equals("开放")) {
                    wifi(ssid, "");
                    Toast.makeText(pew.this, "提交成功", Toast.LENGTH_SHORT).show();
                    adapter.clear();

                } else if (jmfs.equals("加密")) {
                    tck(ssid);
                } else {
                    Toast.makeText(pew.this, "错误未知", Toast.LENGTH_SHORT).show();

                }
                Toast.makeText(pew.this, "第" + position + "个item", Toast.LENGTH_SHORT).show();

//                }

            }
        });
        daa = (ImageButton) findViewById(R.id.lpos);
        daa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ddList.clear();
                Intent intent = new Intent();
                intent.setClass(pew.this, esppew.class);
                startActivity(intent);
            }
        });
        ble = (ImageButton) findViewById(R.id.ble);
        ble.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ddList.clear();
                Intent intent = new Intent();
                intent.setClass(pew.this, ble.class);
                startActivity(intent);
            }
        });
        adapter.setOnItemxxxxClickListener(new adapterwifi.xxxx() {
            @Override
            public void onxxxxClick(int i) {

                LayoutInflater factory = LayoutInflater.from(pew.this);

                final View DialogView = factory.inflate(R.layout.tckk, null);

                TextView SSID = DialogView.findViewById(R.id.SSID);
                SSID.setText(able.get(i).SSID);
                TextView BSSID = DialogView.findViewById(R.id.BSSID);
                BSSID.setText(String.valueOf(able.get(i).BSSID));
                TextView capabilities = DialogView.findViewById(R.id.capabilities);
                capabilities.setText(String.valueOf(able.get(i).capabilities));
                TextView level = DialogView.findViewById(R.id.level);
                level.setText(String.valueOf(able.get(i).level));
                TextView name = DialogView.findViewById(R.id.name);
                name.setText(String.valueOf(able.get(i).frequency));
//    AlertDialog.Builder builder=new AlertDialog.Builder(pew.this);
                AlertDialog dlg = new AlertDialog.Builder(pew.this).setTitle("详细信息显示").setView(DialogView)//设置自定义对话框的样式

                        .create();//创建弹出框
                dlg.show();//显示
            }

        });

    }

    private void two() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String WEBAPI = sharedPreferences.getString("WEBAPI", "");
        Boolean OO = sharedPreferences.getBoolean("wifiabd", false);
        adapter.clear();

        new Thread() {
            @Override
            public void run() {
                super.run();

                request request = new request();
                String resq = request.get(WEBAPI);


                Log.d(TAG, resq);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                    String name = "";
                        try {
                            JSONObject jsonObjectc = new JSONObject(resq);
                            int itme = jsonObjectc.optInt("itme");
                            if (itme == 0) {
                                Toast.makeText(pew.this, "没有设备", Toast.LENGTH_LONG).show();


                            }
                            for (int i = 0; i < itme; i++) {
                                String aadd = jsonObjectc.optString("data" + i);

                                JSONObject jsonObject = new JSONObject(aadd);
                                getValue dd = new getValue();
                                String zt = jsonObject.optString("SSID");
                                String idd = jsonObject.optString("RSSI");
                                int xhqd = jsonObject.optInt("RSSI");
                                System.out.println("a" + xhqd);
                                String aa = jsonObject.optString("clientid");
                                String zz = jsonObject.optString("JMFS");
                                if (xhqd < -85 & xhqd >= -100) {
                                    dd.setTupian(R.drawable.wifia);
                                } else if (xhqd < -70 & xhqd >= -85) {
                                    dd.setTupian(R.drawable.wifib);
                                } else if (xhqd < -55 & xhqd >= -70) {
                                    dd.setTupian(R.drawable.wific);
                                } else if (xhqd <= 0 & xhqd >= -55) {
                                    dd.setTupian(R.drawable.wifid);
                                } else {
                                    dd.setTupian(R.drawable.wifia);

                                }
                                dd.setsbmc(idd);
                                dd.setas(zt);
                                dd.setdyzt(zz);
                                ddList.add(dd);
                                Log.d(TAG, resq);
                            }

                            listView.setAdapter(adapter);
                            // 封装Java对象

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }.start();
    }

    private void wifi(String SSID, String PAWWER) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        String WiFiAPI = sharedPreferences.getString("WiFiAPI", "");


        new Thread() {
            @Override
            public void run() {
                super.run();
                JSONObject jsonObject = new JSONObject();

                try {
                    jsonObject.put("ssid", SSID);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                try {
                    jsonObject.put("password", PAWWER);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                request request = new request();
                String data = null;
                try {
                    data = jsonObject.toString(1);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                String resq = request.post(WiFiAPI, data);
                Log.d(TAG, resq);
                Log.d(TAG, data);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }
        }.start();
    }

    public void tck(String v) {
//    edit_one = (EditText) findViewById(R.id.edit_one);
        LayoutInflater factory = LayoutInflater.from(pew.this);


        final View DialogView = factory.inflate(R.layout.exie, null);


//    AlertDialog.Builder builder=new AlertDialog.Builder(pew.this);
        AlertDialog dlg = new AlertDialog.Builder(pew.this).setTitle(v + "请输入密码").setView(DialogView)//设置自定义对话框的样式
                .setPositiveButton("确定", //设置"确定"按钮
                        new DialogInterface.OnClickListener() //设置事件监听
                        {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //输入后点击“确定”，开始获取我们要的内容 DialogView就是AlertDialog弹出的Activity
                                EditText edtUserName = (EditText) DialogView.findViewById(R.id.password);
                                String pawer = edtUserName.getText().toString();
                                if (!pawer.equals("")) {
                                    Toast.makeText(pew.this, "提交成功", Toast.LENGTH_LONG).show();
                                    adapter.clear();

                                    wifi(v, pawer);
                                } else {
                                    Toast.makeText(pew.this, "请输入密码", Toast.LENGTH_LONG).show();

                                }

//                            Log.d(TAG, pawer);
                            }
                        })
//            .setNeutralButton("无密码",
//                    new DialogInterface.OnClickListener()
//                    {
//                        public void onClick(DialogInterface dialog, int whichButton) {
////
////                            String pawer="";
//////                            wifi(v,pawer);
//                        }
//                    })
                .create();//创建弹出框
        dlg.show();//显示


    }

    void scawifi() {
        WifiManager mWifiManager;
        LocationManager locationManager;
        if (ContextCompat.checkSelfPermission(pew.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(pew.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                Toast.makeText(pew.this, "请同意权限并打开定位和WiFi", Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.WRITE_SETTINGS}, 10000);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.WRITE_SETTINGS}, 10000);
            }
        }

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        boolean ok = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!ok) {
            Toast.makeText(pew.this, "请打开定位", Toast.LENGTH_LONG).show();
            adapter.clear();
        } else {
            mWifiManager.startScan(); //启动扫描
            if (ActivityCompat.checkSelfPermission(pew.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            List<ScanResult> scanResults = mWifiManager.getScanResults();//搜索到的设备列表
            for (int i = 0; i < scanResults.size() - 1; i++) {
                for (int j = 0; j < scanResults.size() - 1 - i; j++) {
                    if (scanResults.get(j).level <= scanResults.get(j + 1).level) {
                        Collections.swap(scanResults, j, j + 1);

                    }
                }

            }
            able = scanResults;
            adapter.clear();
            String ESS = "";
            for (int i = 0; i < scanResults.size(); i++) {
                int xhqd = scanResults.get(i).level;
//                            wifi(scanResults.get(i).SSID,scanResults.get(i).BSSID, String.valueOf(scanResults.get(i).level));
//                            adapter.clear();
                getValue dd = new getValue();
                String a = String.valueOf(scanResults.get(i).level);
                if (Math.abs(xhqd) >= 85 & Math.abs(xhqd) <= 100) {
                    dd.setTupian(R.drawable.wifia);
                } else if (Math.abs(xhqd) >= 70 & Math.abs(xhqd) <= 85) {
                    dd.setTupian(R.drawable.wifib);
                } else if (Math.abs(xhqd) >= 55 & Math.abs(xhqd) <= 70) {
                    dd.setTupian(R.drawable.wific);
                } else if (Math.abs(xhqd) >= 0 & Math.abs(xhqd) <= 55) {
                    dd.setTupian(R.drawable.wifid);
                } else {
                    dd.setTupian(R.drawable.wifid);
                }
                String b = scanResults.get(i).SSID;
                String c = scanResults.get(i).capabilities;

                if (c.equals("[ESS]")) {
                    ESS = "开放";
                } else if (!c.equals("[ESS]")) {
                    ESS = "加密";
                }

                dd.setsbmc(a);
                dd.setas(b);
                dd.setdyzt(ESS);
                ddList.add(dd);
                System.out.println(scanResults.get(i));
            }
            listView.setAdapter(adapter);
        }
    }

}